package gui.user;

import database.TableDatabaseUsage;
import info.Order;
import messages.user.Flight_Refund_Ack_Message;
import messages.user.Flight_Refund_Res_Message;
import server.MessageServer;


import javax.swing.*;

import javax.swing.table.*;
import java.awt.*;
import java.io.IOException;
import java.sql.Date;
import java.util.ArrayList;

import java.util.List;

public class OrderDetailsForm extends JFrame {

    public static JTable ordersTable;
    private String IDNO;
    public OrderDetailsForm(String idno){
        super("订单详情");
        setSize(1500, 300);
        setLayout(new GridLayout(1,1));
        IDNO=idno;
        ordersTable = new JTable(ODFModel1.getInstance(IDNO));
        DefaultTableCellRenderer dc = new DefaultTableCellRenderer();
        dc.setHorizontalAlignment(JLabel.CENTER);
        ordersTable.setDefaultRenderer(Object.class,dc);
        ordersTable.setRowHeight(30);
        ordersTable.getColumnModel().getColumn(8).setCellRenderer(new ButtonRenderer());
        ordersTable.getColumnModel().getColumn(8).setCellEditor(new ButtonEditor(this,ordersTable));
        ordersTable.getColumnModel().getColumn(8).setPreferredWidth(200);
        JScrollPane sp = new JScrollPane(ordersTable);


        add(sp);
        setLocationRelativeTo(null);
        this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        this.setVisible(true);

    }


}

class ODFModel extends AbstractTableModel{
    private static ODFModel instance = new ODFModel();

    public static ODFModel getInstance(){
        return instance;
    }

    private String[] columnNames = {"订单号","身份证号", "航班号", "航班日期", "舱位","折扣","订单状态","订单时间","操作"};
    public static List<Order> orderList = TableDatabaseUsage.getInstance().getOrderList();

    @Override
    public int getRowCount() {
        return orderList.size();
    }

    @Override
    public int getColumnCount() {
        return columnNames.length;
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        Order dataInfo = orderList.get(rowIndex);
        if(columnIndex == 0) {
            return dataInfo.getOrderNo();
        } else if(columnIndex == 1) {
            return dataInfo.getIDNO();
        } else if(columnIndex == 2) {
            return dataInfo.getFlight();
        } else if(columnIndex == 3) {
            return dataInfo.getFdate();
        } else if(columnIndex == 4) {
            return dataInfo.getFclass();
        }else if(columnIndex == 5){
            return dataInfo.getDiscount();
        }else if(columnIndex == 6){
            return dataInfo.getOrderState();
        }else if(columnIndex == 7){
            return dataInfo.getOrderTime();
        }else if(columnIndex == 8){
            return " ";
        }
        return null;
    }

    @Override
    public String getColumnName(int column) {
        return columnNames[column];
    }

    @Override
    public boolean isCellEditable(int rowIndex, int columnIndex) {
        if (columnIndex == 8){
            return true;
        }else{
            return super.isCellEditable(rowIndex, columnIndex);
        }
    }
}
class ODFModel1 extends AbstractTableModel{
    private static ODFModel1 instance = new ODFModel1();
    public static List<Order> orderList;
    public String IDNO;
    public static ODFModel1 getInstance(String idno){
        instance.IDNO=idno;
        instance.orderList=TableDatabaseUsage.getInstance().getOrderList1(idno);
        return instance;
    }

    private String[] columnNames = {"订单号","身份证号", "航班号", "航班日期", "舱位","折扣","订单状态","订单时间","操作"};


    @Override
    public int getRowCount() {
        return orderList.size();
    }

    @Override
    public int getColumnCount() {
        return columnNames.length;
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        Order dataInfo = orderList.get(rowIndex);
        if(columnIndex == 0) {
            return dataInfo.getOrderNo();
        } else if(columnIndex == 1) {
            return dataInfo.getIDNO();
        } else if(columnIndex == 2) {
            return dataInfo.getFlight();
        } else if(columnIndex == 3) {
            return dataInfo.getFdate();
        } else if(columnIndex == 4) {
            return dataInfo.getFclass();
        }else if(columnIndex == 5){
            return dataInfo.getDiscount();
        }else if(columnIndex == 6){
            return dataInfo.getOrderState();
        }else if(columnIndex == 7){
            return dataInfo.getOrderTime();
        }else if(columnIndex == 8){
            return " ";
        }
        return null;
    }

    @Override
    public String getColumnName(int column) {
        return columnNames[column];
    }

    @Override
    public boolean isCellEditable(int rowIndex, int columnIndex) {
        if (columnIndex == 8){
            return true;
        }else{
            return super.isCellEditable(rowIndex, columnIndex);
        }
    }
}
class ButtonRenderer implements TableCellRenderer {
    private JButton viewDetailsButton;
    private JButton refundButton;
    private JButton payButton;
    private JButton cancelButton;
    private JPanel panel;

    public ButtonRenderer() {
        viewDetailsButton = new JButton("查看详情");
        refundButton = new JButton("申请退款");
        payButton = new JButton("去付款");
        cancelButton = new JButton("取消订单");
        panel = new JPanel(new GridLayout(1, 2));
        panel.add(viewDetailsButton);
        panel.add(refundButton);
    }

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
        Object statusObj = table.getValueAt(row, 6);
        String orderStatus = null;
        if (statusObj!= null) {
            orderStatus = (String) statusObj;
        }
        panel.removeAll();
        switch (orderStatus) {
            case "已付款":
                panel.add(viewDetailsButton);
                panel.add(refundButton);
                // 根据需要添加其他已付款按钮
                break;
            case "未付款":
                panel.add(payButton);
                panel.add(cancelButton);
                break;
            case "已退款":
            case "已取消":
                panel.setLayout(new GridLayout(1, 1));
                panel.add(viewDetailsButton);
                break;
            default:
                // 处理其他状态或默认情况
                break;
        }
        panel.revalidate(); // 重新验证布局
        panel.repaint(); // 重新绘制组件
        return panel;
    }
}
class ButtonEditor extends DefaultCellEditor {
    private JButton viewDetailsButton;
    private JButton refundButton;
    private JButton payButton;
    private JButton cancelButton;
    private JPanel panel;

    public Date date;
    public ButtonEditor(OrderDetailsForm form,JTable jTable) {
        super(new JTextField());
        viewDetailsButton = new JButton("查看详情");
        refundButton = new JButton("申请退款");
        payButton = new JButton("去付款");
        cancelButton = new JButton("取消订单");
        panel = new JPanel();

        viewDetailsButton.addActionListener(e -> {
            SwingUtilities.invokeLater(() -> new OrderDetailForm(jTable));
        });

        refundButton.addActionListener(e -> {
            int selectedIndex = JOptionPane.showOptionDialog(null,"是否退款","退款申请",
                    JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE,   null,
                    new String[]{"确定","取消"},"确定");
            if (selectedIndex == 0) {
                sendRefundRequest(String.valueOf(jTable.getValueAt(jTable.getSelectedRow(), 0)),
                        String.valueOf(jTable.getValueAt(jTable.getSelectedRow(), 2)),
                        String.valueOf(jTable.getValueAt(jTable.getSelectedRow(), 4)),
                        "申请退款",
                        form);
                ODFModel.orderList = TableDatabaseUsage.getInstance().getOrderList();
                jTable.updateUI();
            }
            ODFModel.orderList = TableDatabaseUsage.getInstance().getOrderList();
            jTable.updateUI();
        });

        cancelButton.addActionListener(e -> {
            int selectedIndex = JOptionPane.showOptionDialog(null,"是否取消订单","订单取消",
                    JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE,   null,
                    new String[]{"确定","取消"},"确定");
            if (selectedIndex == 0) {
                sendRefundRequest(String.valueOf(jTable.getValueAt(jTable.getSelectedRow(), 0)),
                        String.valueOf(jTable.getValueAt(jTable.getSelectedRow(), 2)),
                        String.valueOf(jTable.getValueAt(jTable.getSelectedRow(), 4)),
                        "取消订单",
                        form);
                ODFModel.orderList = TableDatabaseUsage.getInstance().getOrderList();
                jTable.updateUI();
            }
        });


        payButton.addActionListener(e -> {
            int selectedIndex = JOptionPane.showOptionDialog(null,"是否付款","付款页面",
                    JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE,   null,
                    new String[]{"确定","取消"},"确定");
            if (selectedIndex == 0) {
                sendRefundRequest(String.valueOf(jTable.getValueAt(jTable.getSelectedRow(), 0)),
                        String.valueOf(jTable.getValueAt(jTable.getSelectedRow(), 2)),
                        String.valueOf(jTable.getValueAt(jTable.getSelectedRow(), 4)),
                        "去付款",
                        form);
                ODFModel.orderList = TableDatabaseUsage.getInstance().getOrderList();
                jTable.updateUI();
            }
        });
    }



    @Override
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
        Object statusObj = table.getValueAt(row, 6);
        String orderStatus = null;
        if (statusObj!= null) {
            orderStatus = (String) statusObj;
        }
        panel.removeAll();
        switch (orderStatus) {
            case "已付款":
                panel.setLayout(new GridLayout(1,2));
                panel.add(viewDetailsButton);
                panel.add(refundButton);
                // 根据需要添加其他已付款按钮
                break;
            case "未付款":
                panel.setLayout(new GridLayout(1,2));
                panel.add(payButton);
                panel.add(cancelButton);
                break;
            case "已退款":
            case "已取消":
                panel.setLayout(new GridLayout(1, 1));
                panel.add(viewDetailsButton);
                break;
            default:
                // 处理其他状态或默认情况
                break;
        }
        panel.revalidate(); // 重新验证布局
        panel.repaint(); // 重新绘制组件
        return panel;
    }

    private void sendRefundRequest(String orderNo,String flight,String fclass,String btnText,OrderDetailsForm form){
        Flight_Refund_Res_Message refund_req_msg = new Flight_Refund_Res_Message();
        Flight_Refund_Ack_Message refund_ack_msg;

        refund_req_msg.setOrderNo(orderNo);
        refund_req_msg.setFlight(flight);
        refund_req_msg.setFclass(fclass);
        refund_req_msg.setBtnText(btnText);
//        refund_req_msg.setOrderTime(date);
//        System.out.println(date);



        try {
            MessageServer.getInstance().getOos().writeObject(refund_req_msg);
            System.out.println("客户端发送请求成功！"+refund_req_msg);
            refund_ack_msg = (Flight_Refund_Ack_Message) MessageServer.getInstance().
                    getOis().readObject();
            System.out.println("客户端收到服务端的响应成功！"+refund_ack_msg);
        } catch (IOException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }

        if(refund_ack_msg.getBtnText().equals("已退款")){
            if (refund_ack_msg.isSuccess()){
                JOptionPane.showMessageDialog(form,"退款成功!");

//                jTable.updateUI();

            }else {
                JOptionPane.showMessageDialog(form,"退款失败，请重新尝试");
            }
        }

        if(refund_ack_msg.getBtnText().equals("已取消")){
            if (refund_ack_msg.isSuccess()){
                JOptionPane.showMessageDialog(form,"取消成功!");
            }else {
                JOptionPane.showMessageDialog(form,"取消失败，请重新尝试");
            }
        }

    }
}

class OrderDetailForm extends JFrame{
    private JTextField orderNoField;
    private JTextField idNoField;
    private JTextField flightField;

    private JTextField fdateField;
    private JTextField fclassField;
    private JTextField discountField;
    private JTextField orderStateField;
    private JTextField orderTimeField;

    private List<JTextField> jTextFieldList = new ArrayList<>();

    public OrderDetailForm(JTable jTable){
        super("订单详情");
        setSize(500,500);
        setLayout(new GridLayout(8,2));

        initList(jTable);

        JLabel j1 = new JLabel("订单号：");
        JLabel j2 = new JLabel("身份证号：");
        JLabel j3 = new JLabel("航班号：");
        JLabel j4 = new JLabel("航班日期：");
        JLabel j5 = new JLabel("舱位：");
        JLabel j6 = new JLabel("折扣：");
        JLabel j7 = new JLabel("订单状态：");
        JLabel j8 = new JLabel("订票时间：");

        j1.setHorizontalAlignment(SwingConstants.CENTER);
        j2.setHorizontalAlignment(SwingConstants.CENTER);
        j3.setHorizontalAlignment(SwingConstants.CENTER);
        j4.setHorizontalAlignment(SwingConstants.CENTER);
        j5.setHorizontalAlignment(SwingConstants.CENTER);
        j6.setHorizontalAlignment(SwingConstants.CENTER);
        j7.setHorizontalAlignment(SwingConstants.CENTER);
        j8.setHorizontalAlignment(SwingConstants.CENTER);

        add(j1);
        add(orderNoField);
        add(j2);
        add(idNoField);
        add(j3);
        add(flightField);
        add(j4);
        add(fdateField);
        add(j5);
        add(fclassField);
        add(j6);
        add(discountField);
        add(j7);
        add(orderStateField);
        add(j8);
        add(orderTimeField);

        for (int i = 0; i < jTextFieldList.size(); i++) {
            jTextFieldList.get(i).setEditable(false);
        }

        setLocationRelativeTo(null);
        this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        this.setVisible(true);
    }

    private void initList(JTable jTable){
        orderNoField = new JTextField();
        idNoField = new JTextField();
        flightField = new JTextField();
        fdateField = new JTextField();
        fclassField = new JTextField();
        discountField = new JTextField();
        orderStateField = new JTextField();
        orderTimeField = new JTextField();

        jTextFieldList.add(orderNoField);
        jTextFieldList.add(idNoField);
        jTextFieldList.add(flightField);
        jTextFieldList.add(fdateField);
        jTextFieldList.add(fclassField);
        jTextFieldList.add(discountField);
        jTextFieldList.add(orderStateField);
        jTextFieldList.add(orderTimeField);

        int selectedRow = jTable.getSelectedRow();
        if(selectedRow != -1){
            for (int col = 0; col < jTable.getColumnCount() - 1; col++){
                Object value = jTable.getValueAt(selectedRow,col);
                jTextFieldList.get(col).setText(String.valueOf(value));
            }
        }

    }
}
